package mmc.gl.shader;

import static org.lwjgl.opengl.GL20.*;

import java.nio.ByteBuffer;

import org.lwjgl.opengl.GL11;

public class ShaderProgram {
	private final int id;
	
	public ShaderProgram(){
		id = glCreateProgram();
	}
	
	public void attach(Shader shader){
		glAttachShader(id, shader.getId());
	}
	
	public void detach(Shader shader){
		glDetachShader(id, shader.getId());
	}
	
	public void link(){
		try{
			glLinkProgram(id);
			
			if(GL11.GL_TRUE != glGetProgram(id, GL_LINK_STATUS))
				throw new RuntimeException("LINK_STATUS != GL_TRUE");
		}finally{
			printLog();
		}
	}
	
	public void printLog(){
		System.out.print(glGetProgramInfoLog(id, 1024*1024));
	}
	
	public void use(){
		glUseProgram(id);
	}
	
	public static void useDefault(){
		glUseProgram(0);
	}
	
	public void delete(){
		glDeleteProgram(id);
	}
	
	class Uniform{
		int location;
		ByteBuffer name;
		
		Uniform(String name){
			this.name = ByteBuffer.allocateDirect(name.length()*Character.SIZE);
			for(int i=0;i<name.length();i++){
				this.name.put((byte)name.charAt(i));
			}
			this.name.put((byte)0);
			this.name.rewind();
			
			location = glGetUniformLocation(id, this.name);
		}
	}
	
	class Attribute{
		int location;
		ByteBuffer name;
		
		Attribute(String name){
			this.name = ByteBuffer.allocateDirect(name.length()*Character.SIZE);
			for(int i=0;i<name.length();i++){
				this.name.put((byte)name.charAt(i));
			}
			this.name.put((byte)0);
			this.name.rewind();
			
			location = glGetAttribLocation(id, this.name);
		}
	}
}
